var maintenance_list = [];

function removeAddRow() {
    $("#addRecord").remove();
    $("#addRecordButtons").remove();
}

function removeEditRow() {
    $("#editRecord").remove();
    $("#editRecordButtons").remove();
}

function printRecordRow(row) {
    var column1 = '<td ><span id="span_edit_' + row.id + 
        '" class="hoverButton">Edit</span><span id="span_history_' +
        row.id+'" class="hoverButton" style="margin-top:15px;">History</span>'+
        row.status+'</td>';
    var column2 = '<td >' + row.vehicleno + '</td>';
    var column3 = '<td >' + row.tagno + '</td>';
    var column4 = '<td align="right">' + formatLargeNumbers(row.mileage) + 
        '</td>';
    var column5 = '<td >' + militaryTime(row.start) + '<br>'+
        $.y4m2d2_to_d2m3y4(row.start)+'</td>';
    var column6 = '<td >' + militaryTime(row.finish) + '<br>'+
        $.y4m2d2_to_d2m3y4(row.finish)+'</td>';
    var column7 = '<td >' + row.location +'</td>';
    var column8 = '<td >' + row.reason +' </td>';
    if (row.tow == "True"){
        var column9 = '<td align="center" >'+
            '<img src="/tmpo/images/icons/check.gif"</td>';
    } else {
        column9 = '<td >&nbsp;</td>';
    }
    if (row.accident == "True"){
        var column10 = '<td align="center" >'+
        '<img src="/tmpo/images/icons/check.gif"</td>';
    } else {
        column10 = '<td >&nbsp;</td>';
    }
    $("#maintLog").append('<tbody id="tbody_'+row.id+'"><tr>'+
        column1+column2+column3+column4+column5+column6+column7+column8+
        column9+column10+'</tr></tbody>');
}

function validateForm(last_btn) {
    var error_count = 0;
    $("#message").remove();
    $("td[class='tableErrorColor']").removeClass("tableErrorColor");
    $("span[class='errorMessage']").remove();
    $("input[class='formError']").removeClass('formError');
    $("select[class='formError']").removeClass('formError');
    $("td br").remove();
    var timeError = "Please use four-digit military time. Example: 1430 ";
    if( !$.is_24hour($("#startTime").val())) {
        error_count++;
        $("#startTime").parent().append('<br/><span class="errorMessage">'+
            timeError+'</span>');
        $("#startTime").parent().addClass("tableErrorColor");
        $("#startTime").addClass("formError");
    } else {
        var startTime = $.is_24hour($("#startTime").val());
    }    
    if( !$.is_24hour($("#endTime").val())) {
        error_count++;
        $("#endTime").parent().append('<br/><span class="errorMessage">'+
            timeError+'</span>');
        $("#endTime").parent().addClass("tableErrorColor");
        $("#endTime").addClass("formError");
    } else {
        var endTime = $.is_24hour($("#endTime").val());
    }    
    var dateError = "Please enter a complete date.<br>Example: 01 JAN 2000";
    if( !$.is_d2m3y4($("#startDate").val())) {
        error_count++;
        $("#startDate").parent().append('<br/><span class="errorMessage">'+
            dateError+'</span>');
        $("#startDate").parent().addClass("tableErrorColor");
        $("#startDate").addClass("formError");
    } else {
        var startDate = $.is_d2m3y4($("#startDate").val());
    }
    if( !$.is_d2m3y4($("#endDate").val())) {
        error_count++;
        $("#endDate").parent().append('<br/><span class="errorMessage">'+
            dateError+'</span>');
        $("#endDate").parent().addClass("tableErrorColor");
        $("#endDate").addClass("formError");
    } else {
        var endDate = $.is_d2m3y4($("#endDate").val());
    }    
    if  ((endTime < startTime) && (startDate == endDate)) {
        timeError = "Time Return must be later than Time Wanted.";
        error_count++;
        $("#startTime").parent().append('<br/><span class="errorMessage">'+
            timeError+'</span>');
        $("#startTime").parent().addClass("tableErrorColor");
        $("#startTime").addClass("formError");
        $("#endTime").parent().append('<br/><span class="errorMessage">'+
            timeError+'</span>');
        $("#endTime").parent().addClass("tableErrorColor");
        $("#endTime").addClass("formError");
    }    
    if (startDate > endDate) {
        dateError = "Finish date must be on or after start date.";
        error_count++;
        $("#startDate").parent().append('<br/><span class="errorMessage">'+
            dateError+'</span>');
        $("#startDate").parent().addClass("tableErrorColor");
        $("#startDate").addClass("formError");
        $("#endDate").parent().append('<br/><span class="errorMessage">'+
            dateError+'</span>');
        $("#endDate").parent().addClass("tableErrorColor");
        $("#endDate").addClass("formError");
    }
    var locationReq = "Please enter a service location.";
    if( !$("#location").val() ) {
        error_count++;
        $("#location").parent().append('<br><span class="errorMessage">'+
            locationReq+'</span>');
        $("#location").parent().addClass("tableErrorColor");
        $("#location").addClass("formError");
     }
    var mileageReq = "Please enter vehicle mileage.";
    if( ($("#mileage").val() === 0) || ($("#mileage").val() === "") ) {
        error_count++;
        $("#mileage").parent().append('<br><span class="errorMessage">'+
            mileageReq+'</span>');
        $("#mileage").parent().addClass("tableErrorColor");
        $("#mileage").addClass("formError");
     }        
    if(error_count){    
        $("#" + last_btn).after('<span class="generalErrorMessage" '+
            'name="message" id="message"><img alt="" src="/tmpo/images/'+
            'icons/alert.gif"/>Please correct errors above to save '+
            'maintenance data.</span>');
    } else {
        $("#message").remove();
        $("#" + last_btn).after(
                '<span id="message" name="message" class="waitMessage">'+
                '<img src="/tmpo/images/icons/hourglass.gif" alt="" />'+
                'Your changes are being saved. Please wait.</span>');
        return true;
    }
}

function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json){
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name +'</a> '+
                      'Phone: (' + json.tmpo_poc_phone.substr(0,3) + ') ' +
                      json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    ); 
}

function getRecords() {
    $.ajax({ 
        url: '/api/tmpo/vehicles/maintinfo/', 
        type: "GET", 
        dataType: "json", 
        async: false, 
        success: function(json){
            maintenance_list = $(json.maintenance); 
        }
    });
}

function printRecords() {
    $("#maintLogtbody").remove();
    if(!maintenance_list.length){ 
        $("#maintLog").append(
        '<tbody><tr><td colspan="10">There are no vehicles currently '+
        'listed</td></tr></tbody>');
    }else{ 
        jQuery.map(maintenance_list, function(row){ 
            printRecordRow(row); 
        }); 
    }
    $("#button_print").click(function() {
        $("#maintLog thead tr th:nth-child(9)").remove();
        $("#maintLog thead tr th:nth-child(9)").remove();
        $("#maintLog tbody tr td:nth-child(9)").remove();
        $("#maintLog tbody tr td:nth-child(9)").remove();
        $("#maintLog tbody tr td:nth-child(1) span").remove();
        makePrinter("#maintLog")();
        resetTable();
        return false;
    });
}

function getAndPrintVehicles() {
    $.getJSON(
        '/api/tmpo/vehicles/', 
        function(json){
            jQuery.map(json.vehicles, function(row){
                $("#vehicle_id").append('<option value="'+
                row.id+'">'+row.vehicleno+'</option>');
            });
    });
}

function getAndPrintStatusType(value) {
    var url = '/api/tmpo/vu_type/';
        
    $.getJSON(
        '/api/tmpo/vu_type/', 
        function(json){
            jQuery.map(json.types, function(row){
                $("#statustype").append('<option value="'+row.id+'">'+
                    row.description+'</option>');
            });
        $("#statustype option[value='"+value+"']").attr("selected","selected");
    });
}


function addRecord() {
    var form_data_insert_record = {    
        status: $("#statustype").val(),
        vehicle_id: $("#vehicle_id").val(),
        mileage: $("#mileage").val(),
        start: $.d2m3y4_to_y4m2d2($("#startDate").val())+" "+
            $("#startTime").val().substr(0,2)+
            ":"+$("#startTime").val().substr(2,2),
        finish: $.d2m3y4_to_y4m2d2($("#endDate").val())+" "+
            $("#endTime").val().substr(0,2)+
            ":"+$("#endTime").val().substr(2,2),
        location: $("#location").val(),
        reason: $("#reason").val(),
        tow: $("#tow:checked").length,
        accident: $("#accident:checked").length
    };
    $.ajax({
        url: '/api/tmpo/vehicles/maintinfo/',
        type: "PUT",
        data: form_data_insert_record,
        success: function() {
            console.debug("success");
            resetTable();
        },
        error: function(){
            console.debug("fail");
        }
    });    
}

function updateRecord(key) {
    var form_data_update_record = {
        status: $("#statustype").val(),
        mileage: $("#mileage").val(),
        start: $.d2m3y4_to_y4m2d2($("#startDate").val())+" "+
            $("#startTime").val().substr(0,2)+
            ":"+$("#startTime").val().substr(2,2),
        finish: $.d2m3y4_to_y4m2d2($("#endDate").val())+" "+
            $("#endTime").val().substr(0,2)+
            ":"+$("#endTime").val().substr(2,2),
        location: $("#location").val(),
        location: $("#location").val(),
        reason: $("#reason").val(),
        tow: $("#tow:checked").length,
        accident: $("#accident:checked").length
    };
    $.ajax({
        url: '/api/tmpo/vehicles/maintinfo/'+key+'/',
        type: "POST",
        data: form_data_update_record,
        success: function() {
            console.debug("success");
            resetTable();
        },
        error: function(){
            console.debug("fail");
        }
    });    
}

function deleteRecord(row) {
    var deleteCommitment = function(){
        $.ajax({
            type: "DELETE",
            url: '/api/tmpo/vehicles/maintinfo/'+row.id+'/',
            dataType: "text",
            success: function(){
              resetTable();
            }
        });
        clearTimeout(timeout_index);
        delete timeout_index;
    };
    timeout_index = setTimeout(deleteCommitment, 10000);
    $(window).unload( function (){
        if( typeof(timeout_index) != 'undefined' ){ 
            deleteCommitment();
        }
    });
    $("#editRecord tr").remove();
    $("#editRecordButtons").remove();
    $("#editRecord").append(
        '<tr><td colspan="10"><b>This record has been deleted. '+
        '<span id="close_delete_' + row.id + '" class="inferLink">'+
        '<u>Close</u></span> | <span id="undo_delete_' + row.id + 
        '" class="inferLink"><u>Undo</u></span></b></td></tr>');
    bindRows();
    $("#close_delete_" + row.id).click(function () {
        deleteCommitment(); 
        resetTable();
        return false;
    });
    $("#undo_delete_" + row.id).click(function () {
        clearTimeout(timeout_index); 
        delete timeout_index;
        resetTable(); 
        return false;
    });
}

function printAddRecord() {
    resetTable();
    $("#maintLog tbody").unbind();

    var column1 = '<td><select id="statustype" name="statustype">'+
        '</select></td>';
    var column2 = '<td><select id="vehicle_id" name="vehicle_id">'+
        '</select></td>';
    var column3 = '<td><span id="addTagno"></span></td>';
    var column4 = '<td><input id="mileage" value="0" type="text" '+
        'size="8"></td>';
    var column5 = '<td><input id="startTime" type="text" size="4">'+
        '<h6>0000</h6><input id="startDate" type="text" size="9">'+
        '<h6>DD MMM YYYY</h6></td>';
    var column6 = '<td><input id="endTime" type="text" size="4">'+
        '<h6>0000</h6><input id="endDate" type="text" size="9">'+
        '<h6>DD MMM YYYY</h6></td>';
    var column7 = '<td><input id="location" type="text" size="12">'+
        '<br></td>';
    var column8 = '<td><textarea id="reason" cols="15" rows="2"></textarea>'+
        '</td>';
    var column9 = '<td align="center"><input id="tow" type="checkbox"></td>';
    var column10 = '<td align="center"><input id="accident" type="checkbox">'+
        '</td>';
    $("thead").after(
        '<tbody class="tableActiveColor" name="addRecord" id="addRecord"><tr>'+
        column1+column2+column3+column4+column5+column6+column7+column8+
        column9+column10+'</tr></tbody><tbody class="tableActiveColor" '+
        'id="addRecordButtons"><tr><td colspan="10"><span id="button_save"'+
        ' name="button_save" class="button"><img '+
        'src="/tmpo/images/icons/save.gif" alt="">Save</span><span '+
        'id="button_cancel" name="button_cancel" class="button">'+
        '<img src="/tmpo/images/icons/close.gif" alt="">Cancel</span>'+
        '</td></tr></tbody>');    
    getAndPrintVehicles();
    getAndPrintStatusType();
}

function editRecord(row) {
    $("#maintLog tbody").unbind();
    $("#maintLog tbody tr td").unbind();
	toggleButtons(false);
    var column1 = '<td><span id="span_edit_' + row.id + 
        '" class="hoverButton">Edit</span><span id="span_history_' + 
        row.id+'" class="hoverButton" style="margin-top:15px;">History</span>'+
        '<select id="statustype" name="statustype"></select></td>';
    var column2 = '<td>'+row.vehicleno+'</td>';
    var column3 = '<td>'+row.tagno+'</td>';
    var column4 = '<td><input id="mileage" value="'+row.mileage+'" type="text" '+
        'size="8"></td>';
    var column5 = '<td><input id="startTime" type="text" size="4" value="'+
        militaryTime(row.start)+'"><h6>0000</h6><input id="startDate" '+
        'type="text" size="9" value="'+$.y4m2d2_to_d2m3y4(row.start)+
        '"><h6>DD MMM YYYY</h6></td>';
    var column6 = '<td><input id="endTime" type="text" size="4" value="'+
        militaryTime(row.finish)+'"><h6>0000</h6><input id="endDate" '+
        'type="text" size="9" value="'+$.y4m2d2_to_d2m3y4(row.finish)+
        '"><h6>DD MMM YYYY</h6></td>';
    var column7 = '<td><input id="location" type="text" size="12" value="'+
        row.location+'"><br></td>';
    var column8 = '<td><textarea id="reason" cols="15" rows="2">'+
        row.reason+'</textarea></td>';
    if ( row.tow == "True" ) { 
        var column9 = '<td align="center"><input checked="checked" id="tow" '+
            'type="checkbox"></td>'; 
    }else { 
        column9 = '<td align="center"><input id="tow" type="checkbox">'+
            '</td>'; 
    }
    if ( row.accident == "True" ) { 
        var column10 = '<td align="center"><input checked="checked" '+
            'id="accident" type="checkbox"></td>'; 
    }else { 
        column10 = '<td align="center"><input id="accident" '+
            'type="checkbox"></td>'; 
    }
    $("#tbody_" + row.id).replaceWith(
        '<tbody class="highlight" name="editRecord" id="editRecord"><tr>'+
        column1+column2+column3+column4+column5+column6+column7+column8+
        column9+column10+'</tr></tbody><tbody class="tableActiveColor" '+
        'id="editRecordButtons"><tr><td colspan="10"><span id="button_save"'+
        ' name="button_save" class="button"><img src="/tmpo/images/icons/'+
        'save.gif" alt="">Save</span><span id="button_cancel" '+
        'name="button_cancel" class="button"><img src="/tmpo/images/icons/'+
        'close.gif" alt="">Cancel</span><span id="button_delete" '+
        'name="button_delete" class="button"><img src="/tmpo/images/icons/'+
        'delete.gif" alt="">Delete</span></td></tr></tbody>');
    $("#span_edit_" + row.id).addClass('inactive');
    $("#span_history_" + row.id).click(
        function () { 
            location.href = "/tmpo/vehicles/history/?id="+row.id+
                "&date=current";
        }
    );
    getAndPrintStatusType(row.type);
    $("#button_cancel").click(
        function () { 
			toggleButtons(true);
			resetTable(); 
	});        
    $("#button_save").click(
        function(){
            if( validateForm('button_delete') ){  
                 toggleButtons(true);
				 updateRecord(row.id);
            }
            return false;
    });        
    $("#button_delete").click(
        function () { 
			toggleButtons(true);
			deleteRecord(row);
			return false;
	});

bindAutoDate("#startDate")
bindAutoTime("#startTime")
bindAutoDate("#endDate")
bindAutoTime("#endTime")




}

function setRowColors() {
    $("#maintLog tbody").removeClass('tableErrorColor');
    $("#maintLog tbody").removeClass('tableAlternateColor');
    $("#maintLog tbody:odd").addClass('tableAlternateColor');
    $("#maintLog tbody:contains('On Hold')").addClass('tableErrorColor');     
}

function bindRows() {
    jQuery.map(maintenance_list, function(row){
        if( $("#tbody_"+row.id+":has[class!='highlight']").length ){
            $("#tbody_" + row.id).unbind();
            $("#tbody_" + row.id).hover(
                function () { 
                    $("#tbody_" + row.id).addClass('highlight'); 
                },
                function () { 
                    $("#tbody_" + row.id).removeClass('highlight'); 
            });
            $("#span_history_"+ row.id).click(function () {
                location.href = "/tmpo/vehicles/history/?id="+
                row.id+"&date=current";
            });
            $("#span_edit_" + row.id).click(function () { 
                editRecord(row); 
            });
            $("#tbody_" + row.id+ " tr td").click(function () { 
                editRecord(row); 
            });
            $("#tbody_" + row.id + " tr td span").parent().unbind();        
        }  
    });
}

function resetTable() {
    removeAddRow();
    removeEditRow();
    maintenance_list = [];
    $("#maintLog tbody").remove();
    getRecords();
    printRecords();
    setRowColors();
    bindRows();
}

function toggleButtons(x) {
    if (x===false){
        $("#addRecordInline").unbind();
        $("#button_print").unbind();
        $("#addRecordInline").addClass('buttonInactive');
        $("#button_print").addClass('buttonInactive');
    }else{
        $("#addRecordInline").click(function(){
            toggleButtons(false);
            printAddRecord();
            $("#button_save").click(function(){
                if( validateForm('button_cancel') ){  
                    toggleButtons(true);
                    addRecord();
                }
                return false;
            });
            $("#button_cancel").click(function(){
                toggleButtons(true);
                resetTable();
                return false;
            });
            return false;
        });
        $("#button_print").click(function() {
        $("#maintLog thead tr th:nth-child(9)").remove();
        $("#maintLog thead tr th:nth-child(9)").remove();
        $("#maintLog tbody tr td:nth-child(9)").remove();
        $("#maintLog tbody tr td:nth-child(9)").remove();
        $("#maintLog tbody tr td:nth-child(1) span").remove();
        makePrinter("#maintLog")();
        resetTable();
        });
        $("#addRecordInline").removeClass('buttonInactive');
        $("#button_print").removeClass('buttonInactive');
    }
}

function bindAutoDate(selector) {
    $(selector).blur(function (e) {
        var v = $(selector).val()
        var sv = v.split(/\W+/).filter(function (f) { return (!!f) })
        if (sv[0]) {
            if (sv[0].length==1) {sv[0]="0"+sv[0]}
        }
        if (!sv[2]) {
            sv[2] = "" + new Date().getFullYear();
        }
        $(selector).val(sv.join(" "))
    })
}


function bindAutoTime(selector) {
    $(selector).blur(function (e) {
        var v = $(selector).val()
        if (v.length==3) { $(selector).val("0" + v)}
    })
}


$(document).ready(function() {
    Functional.install();
    getSiteCfg();
    getRecords();
    printRecords();
    setRowColors();
    bindRows();
    $("#addRecordInline").click( function(){
        toggleButtons(false);
        printAddRecord();
        $("#button_save").click( function(){
            if ( validateForm('button_cancel') ){
                toggleButtons(true);
                addRecord();
            }
            return false;
        });
        $("#button_cancel").click( function(){
            toggleButtons(true);
            resetTable();
            return false;
        });
        return false;
    });
});
